package com.ruoyi.feike.service.impl;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.stream.CollectorUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.ruoyi.activiti.service.impl.ActTaskServiceImpl;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.feike.domain.*;
import com.ruoyi.feike.domain.vo.KeepVO;
import com.ruoyi.feike.mapper.*;
import com.ruoyi.feike.service.IAnnualReviewyService;
import com.ruoyi.feike.service.IKeepTempSerivce;
import lombok.extern.slf4j.Slf4j;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.feike.service.INewSumKeepService;
import org.springframework.transaction.annotation.Transactional;

/**
 * feikeService业务层处理
 *
 * @author zmh
 * @date 2022-08-31
 */
@Service
@Slf4j
public class NewSumKeepServiceImpl implements INewSumKeepService
{
    @Autowired
    private NewSumKeepMapper newSumKeepMapper;

    @Autowired
    private INewSumKeepService newSumKeepService;

    @Autowired
    private IKeepTempSerivce keepTempSerivce;

    @Autowired
    private InstanceIdUtil instanceIdUtil;

    @Autowired
    private TaskService taskService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private ProcessRuntime processRuntime;

    @Autowired
    private ActTaskServiceImpl actTaskService;

    @Autowired
    private NotesMapper notesMapper;

    @Autowired
    private AnnualReviewyMapper annualReviewyMapper;

    @Autowired
    private HNewSumKeepModifyMapper hNewSumKeepModifyMapper;

    @Autowired
    private BasicInformationMapper basicInformationMapper;


    @Autowired
    private IAnnualReviewyService annualReviewyService;

    /**
     * 查询feike
     *
     * @param id feikeID
     * @return feike
     */
    @Override
    public NewSumKeep selectNewSumKeepById(String id)
    {
        return newSumKeepMapper.selectNewSumKeepById(id);
    }

    /**
     * 查询feike列表
     *
     * @param newSumKeep feike
     * @return feike
     */
    @Override
    public List<PaidSum> selectNewSumKeepList(NewSumKeep newSumKeep)
    {
        ArrayList<PaidSum> result = new ArrayList<>();
        try {
            if(newSumKeep.getOldPlanRate()!= null && newSumKeep.getOldPlanRate().length()>2 && newSumKeep.getPlanRate()!=null){
                String oldPlanRate = newSumKeep.getOldPlanRate().replace("%", "");
                String planRate = newSumKeep.getPlanRate().replace("%", "");
                if(Double.valueOf(planRate)>Double.valueOf(oldPlanRate)){
                    NewSumKeep newSumKeep2 = new NewSumKeep();
                    newSumKeep2.setDealerName(newSumKeep.getDealerName());
                    newSumKeep2.setSector(newSumKeep.getSector());
                    List<NewSumKeep> newSumKeeps = newSumKeepMapper.selectNewSumKeepList4(newSumKeep2);
                    if(newSumKeeps!=null && newSumKeeps.size()>0){
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        for (NewSumKeep sumKeep : newSumKeeps) {
                            if(sumKeep.getExpiryDate().getTime()>=new Date().getTime()){
                                PaidSum paidSumObj = new PaidSum();
                                paidSumObj.setDealerId(sumKeep.getId());

                                paidSumObj.setDealerName(newSumKeep.getDealerName());
                                paidSumObj.setSector(newSumKeep.getSector());
                                String format1 = sdf.format(new Date());
                                Date parse = sdf.parse(format1);
                                if(sumKeep.getEffectiveDate().getTime()>parse.getTime()){
                                    paidSumObj.setEffectiveDate(sumKeep.getEffectiveDate());
                                }else{
                                    paidSumObj.setEffectiveDate(parse);
                                }
                                paidSumObj.setExpiryDate(sumKeep.getExpiryDate());
                                paidSumObj.setSum(sumKeep.getSum().toString());
                                paidSumObj.setRate(newSumKeep.getPlanRate());
                                long time = sumKeep.getExpiryDate().getTime() - paidSumObj.getEffectiveDate().getTime();
                                String startStr = sdf.format(paidSumObj.getEffectiveDate());
                                String endStr = sdf.format(sumKeep.getExpiryDate());
                                boolean runnian =false;
                                List<String> yearList = DayUtils.getYearBetweenDate(startStr, endStr);
                                List<String> runList = new ArrayList<>();
                                for (String s : yearList) {
                                    runList.add(s+"-02-29");
                                }
                                List<String> everyday = DayUtils.getEveryday(startStr, endStr);
                                if(runList.size()>0){
                                    for (String s : runList) {
                                        if(everyday.contains(s) && !endStr.equals(s)){
                                            runnian = true;
                                            System.out.println("闰年");
                                            break;
                                        }
                                    }
                                }
                                long days = (int) (time /(24
                                        * 60 * 60 * 1000));
                                Double l = Double.valueOf(planRate) - Double.valueOf(oldPlanRate);
                                double paidSum =0l;
                                if(runnian){
                                    paidSum = (days + 1) * sumKeep.getSum() * l / 100 / 366;
                                }else{
                                    paidSum = (days + 1) * sumKeep.getSum() * l / 100 / 365;
                                }
                                BigDecimal bigDecimal = new BigDecimal(paidSum).setScale(2, BigDecimal.ROUND_HALF_UP);
                                /*DecimalFormat df1= new DecimalFormat("0.00");
                                String format = df1.format(paidSum);*/
                                paidSumObj.setPaidsum(bigDecimal.toString());
                                result.add(paidSumObj);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public List<NewSumKeep> selectNewSumKeepList2(NewSumKeep newSumKeep)
    {
        return newSumKeepMapper.selectNewSumKeepList(newSumKeep);
    }

    @Override
    public List<NewSumKeep> selectNewSumKeepList3(NewSumKeep newSumKeep)
    {
        return newSumKeepMapper.selectNewSumKeepList3(newSumKeep);
    }

    @Override
    public List<NewSumKeep> selectNewSumKeepList4(NewSumKeep newSumKeep)
    {
        return newSumKeepMapper.selectNewSumKeepList4(newSumKeep);
    }

    @Override
    public List<NewSumKeep> selectInsuranceHistory(NewSumKeep newSumKeep)
    {
        return newSumKeepMapper.selectInsuranceHistory(newSumKeep);
    }


    @Override
    public List<NewSumKeepFour> selectNewSumKeepListFour(NewSumKeep newSumKeep)
    {
        return newSumKeepMapper.selectNewSumKeepListFour(newSumKeep);
    }

    /**
     * 新增feike
     *
     * @param newSumKeep feike
     * @return 结果
     */
    @Override
    public int insertNewSumKeep(NewSumKeep newSumKeep)
    {
        return newSumKeepMapper.insertNewSumKeep(newSumKeep);
    }

    @Override
    public int insertNewSumKeepHis(NewSumKeep newSumKeep)
    {
        return newSumKeepMapper.insertNewSumKeepHis(newSumKeep);
    }

    @Override
    public int insertInsuranceHistory(NewSumKeep newSumKeep)
    {
        return newSumKeepMapper.insertInsuranceHistory(newSumKeep);
    }

    /**
     * 修改feike
     *
     * @param newSumKeep feike
     * @return 结果
     */
    @Override
    public int updateNewSumKeep(NewSumKeep newSumKeep)
    {
        return newSumKeepMapper.updateNewSumKeep(newSumKeep);
    }

    /**
     * 批量删除feike
     *
     * @param ids 需要删除的feikeID
     * @return 结果
     */
    @Override
    public int deleteNewSumKeepByIds(String[] ids)
    {
        return newSumKeepMapper.deleteNewSumKeepByIds(ids);
    }

    @Override
    public int deleteInsuranceHistoryById(String id)
    {
        return newSumKeepMapper.deleteInsuranceHistoryById(id);
    }

    /**
     * 删除feike信息
     *
     * @param id feikeID
     * @return 结果
     */
    @Override
    public int deleteNewSumKeepById(String id)
    {
        return newSumKeepMapper.deleteNewSumKeepById(id);
    }

    @Override
    public List<NewSumKeep> newSumSelect(NewSumKeep newSumKeep) {
        return newSumKeepMapper.selectNewSumKeepList(newSumKeep);
    }

    @Override
    @Transactional
    public int addACt(Map<String, Object> map) {
        Object newSumKeep = map.get("newSumKeep");
        if (newSumKeep != null) {
            List<HNewSumKeepModify> hNewSumKeepModify = (List<HNewSumKeepModify>) newSumKeep;
            String s = JSON.toJSONString(hNewSumKeepModify);
            hNewSumKeepModify = JSON.parseArray(s, HNewSumKeepModify.class);
            for (HNewSumKeepModify newSumKeepModify : hNewSumKeepModify) {
                if(StringUtils.isNotEmpty(newSumKeepModify.getDealername()) && StringUtils.isNotEmpty(newSumKeepModify.getSector())){
                    int i2 = basicInformationMapper.deleteBasicInformationAnnualDealername3(newSumKeepModify.getDealername(),newSumKeepModify.getSector());
                    if(i2 > 0 ){
                        throw  new BaseException("该经销商有正在进行的 保险信息变更 流程，请结束流程后再提交");
                    }
                    int i1 = basicInformationMapper.deleteBasicInformationAnnualDealername2(newSumKeepModify.getDealername(),newSumKeepModify.getSector());
                    if(i1 > 0 ){
                        throw  new BaseException("该经销商有正在进行的 WFS Limit Set-Up 流程，请结束流程后再提交");
                    }
                }
            }
        }

        String processDefinitionKey = instanceIdUtil.getAbbreviationToMap((String) map.get("processDefinitionKey"));
        if(StringUtils.isEmpty(processDefinitionKey)){
            processDefinitionKey = instanceIdUtil.getAbbreviationToMap("InsuranceChange");
        }
        String currentVal = instanceIdUtil.getRedisInstanceId(processDefinitionKey);
        String instanceId = instanceIdUtil.getIstanceId(processDefinitionKey, currentVal);
        String title = "";
        if (StringUtils.isNotNull(map.get("name"))) {
            title =  String.valueOf(map.get("name"));
        } else {
            title = "InsuranceChange";
        }
        Task task = null;
        Authentication.setAuthenticatedUserId(SecurityUtils.getLoginUser()
                .getUser()
                .getUserId()
                .toString());
        if (map.get("caoGao") != null && map.get("caoGao").toString().equals("1")) {
            //草稿行为,不发流程，仅保存
        } else {
            //流程开始
            ProcessInstance processInstance = null;
            if (StringUtils.isNotNull(map.get("processDefinitionKey"))) {
                processInstance = processRuntime.start(ProcessPayloadBuilder
                        .start()
                        .withProcessDefinitionKey("InsuranceChange")
                        .withName(title)
                        .withBusinessKey(instanceId)
                        // .withVariable("deptLeader",join)
                        .build());
            } else {
                processInstance = processRuntime.start(ProcessPayloadBuilder
                        .start()
                        .withProcessDefinitionKey("InsuranceChange")
                        .withName(title)
                        .withBusinessKey(instanceId)
                        // .withVariable("deptLeader",join)
                        .build());
            }


            task = taskService.createTaskQuery()
                    .processInstanceId(processInstance.getId())
                    .singleResult();



            TaskQuery query = taskService.createTaskQuery().taskCandidateOrAssigned(SecurityUtils.getUsername()).active();
            List<Task> todoList = query.list();//获取申请人的待办任务列表
            for (Task tmp : todoList) {
                if (tmp.getProcessInstanceId().equals(processInstance.getId())) {
                    task = tmp;//获取当前流程实例，当前申请人的待办任务
                    break;
                }
            }
            HashMap<String, Object> variables = new HashMap<String, Object>();
//            List<Map<String, Object>> actForm = (List<Map<String, Object>>) map.get("actForm");
//            for (Map<String, Object> form : actForm) {
//                variables.put(String.valueOf(form.get("controlId")), form.get("controlValue"));
//            }
            variables.put("toUnderwriter", 0);
            variables.put("FormProperty_0p5118h", 0);
            taskService.complete(task.getId(), variables);

        }




        //经销商名称
        ArrayList<String> dealerNames = new ArrayList<>();
        //sector
        ArrayList<String> sectors = new ArrayList<>();

        if (newSumKeep != null) {
            List<HNewSumKeepModify> hNewSumKeepModify = (List<HNewSumKeepModify>) newSumKeep;
            String s = JSON.toJSONString(hNewSumKeepModify);
            hNewSumKeepModify = JSON.parseArray(s, HNewSumKeepModify.class);
            for (HNewSumKeepModify newSumKeepModify : hNewSumKeepModify) {
                NewSumKeep newSum = new NewSumKeep();
                newSum.setId(newSumKeepModify.getId());
                newSum.setInTransition(0);
//                if(ObjectUtil.isNotEmpty(newSumKeepModify.getNewsum())){
//                    newSum.setSum(newSumKeepModify.getNewsum());
//                }
//                if(StringUtils.isNotEmpty(newSumKeepModify.getNewplanrate())){
//                    newSum.setPlanRate(newSumKeepModify.getNewplanrate());
//                }
//                if(ObjectUtil.isNotEmpty(newSumKeepModify.getNeweffectivedate())){
//                    newSum.setEffectiveDate(newSumKeepModify.getNeweffectivedate());
//
//                }
//                if(ObjectUtil.isNotEmpty(newSumKeepModify.getNewexpirydate())){
//                    newSum.setExpiryDate(newSumKeepModify.getNewexpirydate());
//                }
                newSumKeepMapper.updateNewSumKeep(newSum);

                newSumKeepModify.setOldid(newSumKeepModify.getId());
                newSumKeepModify.setId(IdUtils.simpleUUID());
                newSumKeepModify.setInstanceId(instanceId);
                newSumKeepModify.setUpdateBy(SecurityUtils.getUsername());
                newSumKeepModify.setUpdateTime(DateUtils.getNowDate());
                hNewSumKeepModifyMapper.insertHNewSumKeepModify(newSumKeepModify);
                annualReviewyService.saveDbLog("1","新增流程","保险信息变更",instanceId,null,newSumKeepModify,null);


                if(StringUtils.isNotEmpty(newSumKeepModify.getDealername())){
                    dealerNames.add(newSumKeepModify.getDealername());
                    BasicInformation basicInformation = new BasicInformation();
                    basicInformation.setId(IdUtils.simpleUUID());
                    basicInformation.setInstanceId(instanceId);
                    basicInformation.setDealerNameCN(newSumKeepModify.getDealername());
                    if(StringUtils.isNotEmpty(newSumKeepModify.getSector())){
                        basicInformation.setSector(newSumKeepModify.getSector());
                    }
                    basicInformationMapper.insertBasicInformation(basicInformation);
                }
            }
        }


        //h_notes ============================================
        Notes notes = new Notes();
        //String notesId = UUID.randomUUID().toString().replace("-", "");
        notes.setId(IdUtils.simpleUUID());
        notes.setInstanceId(instanceId);
        notes.setBasicNotes((String) map.get("basicNotes"));
        notes.setDealerNotes((String) map.get("dealerNotes"));
        notes.setLoyaltyNotes((String) map.get("loyaltyNotes"));
        notes.setAuditNotes((String) map.get("auditNotes"));
        notes.setWholesaleNotes((String) map.get("wholesaleNotes"));
        notes.setProposalNotes((String) map.get("proposalNotes"));
        notes.setGuaranteeNotes((String) map.get("guaranteeNotes"));
        notes.setAmlNotes((String) map.get("amlNotes"));
        notes.setComments((String) map.get("comments"));
        notes.setConditionNotes((String) map.get("conditionNotes"));

        notesMapper.insertNotes(notes);

        AnnualReviewy annualReviewy = new AnnualReviewy();
        annualReviewy.setId(IdUtils.simpleUUID());
        annualReviewy.setTitle(title);
        annualReviewy.setCreateTime(DateUtils.getNowDate());
        annualReviewy.setInstanceId(instanceId);
        annualReviewy.setState("0");
        if (map.get("caoGao") != null && map.get("caoGao").toString().equals("1")) {//草稿行为时
            annualReviewy.setState("3");
        }
        if (StringUtils.isNotNull(map.get("processDefinitionKey"))) {
            annualReviewy.setType(map.get("processDefinitionKey") + "");
        } else {
            annualReviewy.setType("annualVerification");
        }
        annualReviewy.setCreateName(SecurityUtils.getNickName());
        annualReviewy.setCreateBy(SecurityUtils.getUsername());
        annualReviewy.setCreateTime(DateUtils.getNowDate());
        annualReviewy.setType("InsuranceChange");
        if(ObjectUtil.isNotEmpty(task)){
            annualReviewy.setStartNode(task.getName());
        }
       /* ActWorkflowFormData actWorkflowFormData = new ActWorkflowFormData();
        actWorkflowFormData.setBusinessKey(instanceId);
        actWorkflowFormData.setControlName("是否提交");
        actWorkflowFormData.setControlValue("提交");
        actWorkflowFormData.setTaskNodeName(task.getName());
        actWorkflowFormData.setCreateName(SecurityUtils.getNickName());
        actWorkflowFormData.setCreateBy(SecurityUtils.getUsername());
        actWorkflowFormDataService.insertActWorkflowFormData(actWorkflowFormData);*/
        int i = annualReviewyMapper.insertAnnualReviewy(annualReviewy);
        annualReviewyService.saveDbLog("1","新增流程",null ,instanceId,null,annualReviewy,null);


        //非草稿行为，提交流程 发送邮件
        if(map.get("caoGao") == null || !map.get("caoGao").toString().equals("1")){
            //发送邮件
            try {
                org.activiti.engine.runtime.ProcessInstance processInstanceMe = runtimeService.createProcessInstanceQuery()
                        .processInstanceId(task.getProcessInstanceId())
                        .singleResult();
                // 上一个节点的执行完，再次查询，获取下一个节点的任务信息
                org.activiti.engine.task.Task task1 = taskService.createTaskQuery()
                        .processInstanceId(processInstanceMe.getProcessInstanceId())
                        .singleResult();

                ThreadUtil.execute(new Runnable() {

                    @Override
                    public void run() {
                        actTaskService.sendMail(task1, instanceId,null);
                    }
                });

            } catch (Exception e) {
                log.error("邮件发送失败，{}",e.getMessage());
            }
        }

        return i;
    }

    @Override
    public List<HNewSumKeepModify> getByInstanceId(String instanceId) {
        return hNewSumKeepModifyMapper.selectHNewSumKeepModifyListByInstanceId(instanceId);
    }

    @Override
    public void update(Map<String, Object> map) {

        Object newSumKeep = map.get("newSumKeep");

        Object instanceId = map.get("instanceId");


        if (newSumKeep != null) {
            List<HNewSumKeepModify> hNewSumKeepModify = (List<HNewSumKeepModify>) newSumKeep;
            String s = JSON.toJSONString(hNewSumKeepModify);
            hNewSumKeepModify = JSON.parseArray(s, HNewSumKeepModify.class);
            for (HNewSumKeepModify newSumKeepModify : hNewSumKeepModify) {
                NewSumKeep newSum = new NewSumKeep();
                newSum.setId(newSumKeepModify.getOldid());
                if(ObjectUtil.isNotEmpty(newSumKeepModify.getNewsum())){
                    newSum.setSum(newSumKeepModify.getNewsum());
                }
                if(StringUtils.isNotEmpty(newSumKeepModify.getNewplanrate())){
                    newSum.setPlanRate(newSumKeepModify.getNewplanrate());
                }
                if(ObjectUtil.isNotEmpty(newSumKeepModify.getNeweffectivedate())){
                    newSum.setEffectiveDate(newSumKeepModify.getNeweffectivedate());

                }
                if(ObjectUtil.isNotEmpty(newSumKeepModify.getNewexpirydate())){
                    newSum.setExpiryDate(newSumKeepModify.getNewexpirydate());
                }
                //newSumKeepMapper.updateNewSumKeep(newSum);

                newSumKeepModify.setUpdateBy(SecurityUtils.getUsername());
                newSumKeepModify.setUpdateTime(DateUtils.getNowDate());
                hNewSumKeepModifyMapper.updateHNewSumKeepModify(newSumKeepModify);
            }
        }

        //流程修改时间
        if(ObjectUtil.isNotEmpty(instanceId)){
            //HNewSumKeepModify hNewSumKeepModify1 = hNewSumKeepModify.get(0);
            AnnualReviewy annualReviewy = annualReviewyMapper.selectAnnualReviewyByInstanceId(instanceId.toString());
            if(ObjectUtil.isNotEmpty(annualReviewy)){
                annualReviewy.setUpdateTime(DateUtils.getNowDate());
            }
            annualReviewyMapper.updateAnnualReviewy(annualReviewy);
        }

    }

    //封装
    @Override
    public ArrayList<NewSum> newSums(List<LimitActiveProposal> limitActiveProposals,BigDecimal rate,String dealerName,String sector,boolean flag,boolean typeFlag ,String planMethod){
        ArrayList<NewSum> list = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        HashMap<Integer, List<Map<String, Long>>> mapSum = new HashMap<>();
        int i = 0;
        List<String> days =null ;
        for (LimitActiveProposal limitActiveProposal : limitActiveProposals) {
            List<Map<String, Long>> iptList = new ArrayList<>();
            Date start =new Date();
            String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            try{
                start = sdf.parse(format);
            }catch (Exception e){
                e.printStackTrace();
            }
            Date end = limitActiveProposal.getProposedEnd();
            System.out.println(start.getTime());
            System.out.println(end.getTime());
            if(start.getTime()>end.getTime()){
                continue;
            }
            String startStr = sdf.format(start);
            String endStr = sdf.format(end);
            List<String> everyday = DayUtils.getEveryday(startStr, endStr);
            days = everyday;
            for (String s : everyday) {
                HashMap<String, Long> map = new HashMap<>();
                map.put(s,Long.valueOf(limitActiveProposal.getProposalActiveLimit()));
                iptList.add(map);
            }
            mapSum.put(i,iptList);
            i++;
        }
        NewSumKeep sumKeep = new NewSumKeep();
        sumKeep.setDealerName(dealerName);
        sumKeep.setSector(sector);
        if(typeFlag){
            sumKeep.setTempLimit("Y");
        }else{
            sumKeep.setTempLimit("N");
        }
        List<NewSumKeep> newSumKeeps = newSumKeepService.selectNewSumKeepList4(sumKeep);
        HashMap<Integer, List<Map<String, Long>>> mapSum2 = new HashMap<>();
        int m = 0;
        if(newSumKeeps!=null && newSumKeeps.size()>0){
            for (NewSumKeep newSumKeep : newSumKeeps) {
                List<Map<String, Long>> iptList2 = new ArrayList<>();
                Date date = new Date();
                Date expiryDate = newSumKeep.getExpiryDate();
                String startStr = sdf.format(date);
                String endStr = sdf.format(expiryDate);
                List<String> everyday = DayUtils.getEveryday(startStr, endStr);
                for (String s : everyday) {
                    HashMap<String, Long> map = new HashMap<>();
                    map.put(s,Long.valueOf(newSumKeep.getSum()));
                    iptList2.add(map);
                }
                mapSum2.put(m,iptList2);
                m++;
            }
        }		//判断map
        if(i>0){
            ArrayList<KeepVO> keepVOArrayList = new ArrayList<>();
            for (String day : days) {
                KeepVO keepVO = new KeepVO();
                keepVO.setDayTime(day);
                Long AmtNew =0L;
                for (int j = 0; j < i ; j++) {
                    List<Map<String, Long>> mapList = mapSum.get(j);
                    for (Map<String, Long> stringLongMap : mapList) {
                        if(stringLongMap.get(day) !=null){
                            AmtNew = AmtNew+stringLongMap.get(day);
                            break;
                        }
                    }
                }
                keepVO.setNewSum(AmtNew);
                Long AmtHis =0L;
                if(m>0){
                    for (int j = 0; j < m ; j++) {
                        List<Map<String, Long>> mapList = mapSum2.get(j);
                        for (Map<String, Long> stringLongMap : mapList) {
                            if(stringLongMap.get(day) !=null){
                                AmtHis = AmtHis+stringLongMap.get(day);
                                break;
                            }
                        }
                    }
                }
                keepVO.setOutSum(AmtHis);
                Long Limit = 0L;
                if(AmtNew - AmtHis > 0){
                    Limit = AmtNew - AmtHis;
                }
                keepVO.setLimitAmt(Limit);
                if(Limit>0){
                    keepVOArrayList.add(keepVO);
                }
            }

           /* if(keepVOArrayList.size()>0 && keepVOArrayList !=null){
                keepTempSerivce.deleteKeep();
                keepTempSerivce.insertKeeps(keepVOArrayList);
            }*/
            //List<Map<String, Object>> maps = keepTempSerivce.selectKeep();
            //List<KeepVO> keepVOS = keepTempSerivce.selectKeep1();
            ArrayList<HashMap<String, Object>> hashMapsList = new ArrayList<>();
            if(keepVOArrayList!=null&&keepVOArrayList.size()>0) {
                Long amt = 0L;
                int Q = 1;
                int W = 0;
                ArrayList<HashMap<String, Object>> hashMaps = new ArrayList<>();

                HashMap<String, Object> stringObjectHashMap;
                for (KeepVO keepVO : keepVOArrayList) {
                    if (keepVO.getLimitAmt().toString().equals(amt.toString())) {
                        HashMap<String, Object> stringObjectHashMap1 = hashMaps.get(0);
                        stringObjectHashMap1.put("maxDay", keepVO.getDayTime());
                    } else {
                        //创建一个新的
                        if (Q == 1) {
                            stringObjectHashMap = new HashMap<>();
                            stringObjectHashMap.put("minDay", keepVO.getDayTime());
                            stringObjectHashMap.put("maxDay", keepVO.getDayTime());
                            stringObjectHashMap.put("limitAmt", keepVO.getLimitAmt());
                            hashMaps.add(stringObjectHashMap);
                            amt = keepVO.getLimitAmt();
                            Q++;
                        } else {
                            //将原来的进行保存
                            hashMapsList.add(hashMaps.get(0));
                            hashMaps.clear();
                            stringObjectHashMap = new HashMap<>();
                            stringObjectHashMap.put("minDay", keepVO.getDayTime());
                            stringObjectHashMap.put("maxDay", keepVO.getDayTime());
                            stringObjectHashMap.put("limitAmt", keepVO.getLimitAmt());
                            hashMaps.add(stringObjectHashMap);
                            amt = keepVO.getLimitAmt();
                        }
                    }
                    W++;
                    if (String.valueOf(W).equals(String.valueOf(keepVOArrayList.size()))) {
                        hashMapsList.add(hashMaps.get(0));
                        hashMaps.clear();
                    }
                }
            }
            if(hashMapsList !=null && hashMapsList.size()>0){
                for (Map<String, Object> map : hashMapsList) {
                    Date minDate =null ;
                    Date maxDate =null ;
                    Date DateTemp = null;
                    String format = new SimpleDateFormat("YYYY").format(new Date());
                    if(format.equals("2024")){
                        flag = false;
                    }else{
                        flag =true;
                    }
                    String DateTempStr =format+"-05-01";
                    NewSum newSum = new NewSum();
                    newSum.setDealerName(dealerName);
                    newSum.setSector(sector);
                    newSum.setDealerId(IdUtils.simpleUUID());
                    String minDay = map.get("minDay").toString();
                    String maxDay = map.get("maxDay").toString();
                    //计算金额
                    String limitAmt = map.get("limitAmt").toString();
                    boolean run =false;
                    List<String> yearList = DayUtils.getYearBetweenDate(minDay, maxDay);
                    List<String> runList = new ArrayList<>();
                    for (String s : yearList) {
                        runList.add(s+"-02-29");
                    }
                    if(runList.size()>0){
                        List<String> everyday = DayUtils.getEveryday(minDay, maxDay);
                        for (String s : runList) {
                            if(everyday.contains(s)){
                                run = true;
                                System.out.println("闰年");
                                break;
                            }
                        }
                    }
                    newSum.setDayAmt(limitAmt);
                    if(planMethod.equals("缴纳保费")){
                        BigDecimal multiply = new BigDecimal(limitAmt).multiply(rate).setScale(10,BigDecimal.ROUND_HALF_UP);
                        BigDecimal divide1 = new BigDecimal(0);
                        if(run){
                            divide1 = multiply.divide(new BigDecimal(366),BigDecimal.ROUND_HALF_UP).setScale(10,BigDecimal.ROUND_HALF_UP);
                        }else{
                            divide1 = multiply.divide(new BigDecimal(365),BigDecimal.ROUND_HALF_UP).setScale(10,BigDecimal.ROUND_HALF_UP);
                        }
                        //得到一天
                        try{
                            int i1 = DayUtils.daysBetween(minDay, maxDay);
                            BigDecimal bigDecimal = divide1.multiply(new BigDecimal(i1+1)).setScale(2, BigDecimal.ROUND_HALF_UP);
                            newSum.setSumDay(bigDecimal.toString());
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                    try {
                        minDate = sdf.parse(minDay);
                        maxDate = sdf.parse(maxDay);
                        DateTemp = sdf.parse(DateTempStr);
                        newSum.setStartDate(minDate);
                        newSum.setEndDate(maxDate);
                    }catch (Exception e){
                        e.printStackTrace();
                        new BaseException("日期转化异常");
                    }
                    newSum.setSum(map.get("limitAmt").toString());

                    if(minDate.getTime()>=DateTemp.getTime() && flag && planMethod.equals("缴纳保费") ){
                        newSum.setSumDay("-");
                    }
                    if(StringUtils.isEmpty(newSum.getSumDay())){
                        newSum.setSumDay("");
                    }
                    list.add(newSum);
                }
            }
        }

        if(list.size()>0){
            ArrayList<NewSum> list1 = new ArrayList<>();
            for (NewSum newSum : list) {
                //判断开始日期和结束日期是否大于1年
                long day = (newSum.getEndDate().getTime()-newSum.getStartDate().getTime())/(24*60*60*1000);
                if(day>365 && !newSum.getSumDay().equals("-") ){
                    //计算年份
                    try {
                        String startStr = sdf.format(newSum.getStartDate());
                        String endStr = sdf.format(newSum.getEndDate());
                        List<Map<String, String>> cycleList = DayUtils.getCycleList(365, startStr, endStr);
                        if(cycleList!=null && cycleList.size()>0){
                            ArrayList<NewSum> newSums = new ArrayList<>();
                            for (Map<String, String> stringStringMap : cycleList) {
                                Date minDate =null ;
                                Date maxDate =null ;
                                String stStr = stringStringMap.get("startStr");
                                String endstr = stringStringMap.get("endStr");
                                NewSum newSum1 = new NewSum();
                                newSum1.setDealerId(newSum.getDealerId());
                                newSum1.setDealerName(newSum.getDealerName());
                                newSum1.setSector(newSum.getSector());
                                try {
                                    minDate = sdf.parse(stStr);
                                    maxDate = sdf.parse(endstr);
                                    newSum1.setStartDate(minDate);
                                    newSum1.setEndDate(maxDate);
                                    newSum1.setSum(newSum.getSum());

                                    boolean run =false;
                                    List<String> yearList = DayUtils.getYearBetweenDate(stStr, endstr);
                                    List<String> runList = new ArrayList<>();
                                    for (String s : yearList) {
                                        runList.add(s+"-02-29");
                                    }
                                    if(runList.size()>0){
                                        List<String> everyday = DayUtils.getEveryday(stStr, endstr);
                                        for (String s : runList) {
                                            if(everyday.contains(s) && !endstr.equals(s)){
                                                run = true;
                                                System.out.println("闰年");
                                                break;
                                            }
                                        }
                                    }
                                    if(planMethod.equals("缴纳保费")) {
                                        BigDecimal multiply = new BigDecimal(newSum.getDayAmt()).multiply(rate).setScale(10, BigDecimal.ROUND_HALF_UP);
                                        BigDecimal divide1 = new BigDecimal(0);
                                        if (run) {
                                            divide1 = multiply.divide(new BigDecimal(366), BigDecimal.ROUND_HALF_UP).setScale(10, BigDecimal.ROUND_HALF_UP);
                                        } else {
                                            divide1 = multiply.divide(new BigDecimal(365), BigDecimal.ROUND_HALF_UP).setScale(10, BigDecimal.ROUND_HALF_UP);
                                        }
                                        int i1 = DayUtils.daysBetween(stStr, endstr);
                                        BigDecimal bigDecimal = divide1.multiply(new BigDecimal(i1 + 1)).setScale(2, BigDecimal.ROUND_HALF_UP);
                                        newSum1.setSumDay(bigDecimal.toString());
                                    }
                                    newSums.add(newSum1);
                                }catch (Exception e){
                                    e.printStackTrace();
                                    new BaseException("日期转化异常");
                                }
                            }
                            if(newSums!=null && newSums.size()>0){
                                //需要合并
                                BigDecimal huizong = new BigDecimal(0);
                                if(planMethod.equals("缴纳保费")) {
                                    for (NewSum sum : newSums) {
                                        huizong = huizong.add(new BigDecimal(sum.getSumDay()));
                                    }
                                }
                                NewSum newSum2 = new NewSum();
                                newSum2.setDealerId(newSum.getDealerId());
                                newSum2.setDealerName(newSum.getDealerName());
                                newSum2.setSector(newSum.getSector());
                                newSum2.setStartDate(newSum.getStartDate());
                                newSum2.setEndDate(newSum.getEndDate());
                                newSum2.setSum(newSum.getSum());
                                newSum2.setSumDay(huizong.toString());
                                list1.add(newSum2);
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }else{
                    list1.add(newSum);
                }
            }
            return list1;
        }
        return list;
    }

    public ArrayList<NewSum> newSumsTemp(List<LimitActiveProposal> limitActiveProposals,BigDecimal rate,String dealerName,String sector,boolean flag){
        ArrayList<NewSum> list = new ArrayList<>();
        Date DateTemp = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        HashMap<Integer, List<Map<String, Long>>> mapSum = new HashMap<>();

        for (LimitActiveProposal limitActiveProposal : limitActiveProposals) {
            NewSum newSum = new NewSum();
            newSum.setDealerName(dealerName);
            newSum.setSector(sector);
            newSum.setDealerId(IdUtils.simpleUUID());
            // newSum.setSumDay(bigDecimal.toString());
            newSum.setSum(limitActiveProposal.getProposalActiveLimit());
            newSum.setStartDate(limitActiveProposal.getProposedStart());
            newSum.setEndDate(limitActiveProposal.getProposedEnd());
            String minDay = sdf.format(limitActiveProposal.getProposedStart());
            String maxDay = sdf.format(limitActiveProposal.getProposedEnd());
            boolean run =false;
            List<String> yearList = DayUtils.getYearBetweenDate(minDay, maxDay);
            List<String> runList = new ArrayList<>();
            for (String s : yearList) {
                runList.add(s+"-02-29");
            }
            if(runList.size()>0){
                List<String> everyday = DayUtils.getEveryday(minDay, maxDay);
                for (String s : runList) {
                    if(everyday.contains(s)){
                        run = true;
                        System.out.println("闰年");
                        break;
                    }
                }
            }
            newSum.setDayAmt(limitActiveProposal.getProposalActiveLimit());
            BigDecimal multiply = new BigDecimal(limitActiveProposal.getProposalActiveLimit()).multiply(rate).setScale(10,BigDecimal.ROUND_HALF_UP);
            BigDecimal divide1 = new BigDecimal(0);
            if(run){
                divide1 = multiply.divide(new BigDecimal(366),BigDecimal.ROUND_HALF_UP).setScale(10,BigDecimal.ROUND_HALF_UP);
            }else{
                divide1 = multiply.divide(new BigDecimal(365),BigDecimal.ROUND_HALF_UP).setScale(10,BigDecimal.ROUND_HALF_UP);
            }
            //得到一天
            try{
                int i1 = DayUtils.daysBetween(minDay, maxDay);
                BigDecimal bigDecimal = divide1.multiply(new BigDecimal(i1+1)).setScale(2, BigDecimal.ROUND_HALF_UP);
                newSum.setSumDay(bigDecimal.toString());
                String format = new SimpleDateFormat("YYYY").format(new Date());
                if(format.equals("2024")){
                    flag = false;
                }else{
                    flag =true;
                }
                String DateTempStr =format+"-05-01";
                DateTemp = sdf.parse(DateTempStr);
            }catch (Exception e){
                e.printStackTrace();
            }


            if(limitActiveProposal.getProposedStart().getTime()>=DateTemp.getTime() && flag){
                newSum.setSumDay("-");
            }
            list.add(newSum);
        }

        if(list.size()>0){
            ArrayList<NewSum> list1 = new ArrayList<>();
            for (NewSum newSum : list) {
                //判断开始日期和结束日期是否大于1年
                long day = (newSum.getEndDate().getTime()-newSum.getStartDate().getTime())/(24*60*60*1000);
                if(day>365 && !newSum.getSumDay().equals("-")){
                    //计算年份
                    try {
                        String startStr = sdf.format(newSum.getStartDate());
                        String endStr = sdf.format(newSum.getEndDate());
                        List<Map<String, String>> cycleList = DayUtils.getCycleList(365, startStr, endStr);
                        if(cycleList!=null && cycleList.size()>0){
                            ArrayList<NewSum> newSums = new ArrayList<>();
                            for (Map<String, String> stringStringMap : cycleList) {
                                Date minDate =null ;
                                Date maxDate =null ;
                                String stStr = stringStringMap.get("startStr");
                                String endstr = stringStringMap.get("endStr");
                                NewSum newSum1 = new NewSum();
                                newSum1.setDealerId(newSum.getDealerId());
                                newSum1.setDealerName(newSum.getDealerName());
                                newSum1.setSector(newSum.getSector());
                                try {
                                    minDate = sdf.parse(stStr);
                                    maxDate = sdf.parse(endstr);
                                    newSum1.setStartDate(minDate);
                                    newSum1.setEndDate(maxDate);
                                    newSum1.setSum(newSum.getSum());

                                    boolean run =false;
                                    List<String> yearList = DayUtils.getYearBetweenDate(stStr, endstr);
                                    List<String> runList = new ArrayList<>();
                                    for (String s : yearList) {
                                        runList.add(s+"-02-29");
                                    }
                                    if(runList.size()>0){
                                        List<String> everyday = DayUtils.getEveryday(stStr, endstr);
                                        for (String s : runList) {
                                            if(everyday.contains(s) && !endstr.equals(s)){
                                                run = true;
                                                System.out.println("闰年");
                                                break;
                                            }
                                        }
                                    }
                                    BigDecimal multiply = new BigDecimal(newSum.getDayAmt()).multiply(rate).setScale(10,BigDecimal.ROUND_HALF_UP);
                                    BigDecimal divide1 = new BigDecimal(0);
                                    if(run){
                                        divide1 = multiply.divide(new BigDecimal(366),BigDecimal.ROUND_HALF_UP).setScale(10,BigDecimal.ROUND_HALF_UP);
                                    }else{
                                        divide1 = multiply.divide(new BigDecimal(365),BigDecimal.ROUND_HALF_UP).setScale(10,BigDecimal.ROUND_HALF_UP);
                                    }
                                    int i1 = DayUtils.daysBetween(stStr, endstr);
                                    BigDecimal bigDecimal = divide1.multiply(new BigDecimal(i1+1)).setScale(2, BigDecimal.ROUND_HALF_UP);
                                    newSum1.setSumDay(bigDecimal.toString());
                                    newSums.add(newSum1);
                                }catch (Exception e){
                                    e.printStackTrace();
                                    new BaseException("日期转化异常");
                                }
                            }
                            if(newSums!=null && newSums.size()>0){
                                //需要合并
                                BigDecimal huizong = new BigDecimal(0);
                                for (NewSum sum : newSums) {
                                    huizong = huizong.add(new BigDecimal(sum.getSumDay()));
                                }
                                NewSum newSum2 = new NewSum();
                                newSum2.setDealerId(newSum.getDealerId());
                                newSum2.setDealerName(newSum.getDealerName());
                                newSum2.setSector(newSum.getSector());
                                newSum2.setStartDate(newSum.getStartDate());
                                newSum2.setEndDate(newSum.getEndDate());
                                newSum2.setSum(newSum.getSum());
                                newSum2.setSumDay(huizong.toString());
                                list1.add(newSum2);
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }else{
                    list1.add(newSum);
                }
            }
            return list1;
        }
        return list;
    }
}
